<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件比较</title>
</head>
<body>
    <div id="container" style="position: absolute; inset: 0;"></div>
    <script src="./modules/monaco-editor/loader.js"></script>
    <script>
        require.config({ paths: { vs: './modules/monaco-editor/vs' } });

        function groupHex(text){
            const arr = text.split('\n');
            const newarr = [];
            let index=0,prog=0,max=arr.length;
            for (;index < max; ++index) {
                if (index % 4 === 0) newarr.push('# 扇区 ' + (prog++));
                newarr.push(arr[index]);
            }
            return newarr.join('\n');
        }
        async function formatHex(blob) {
            // 读取Blob为ArrayBuffer  
            const arrayBuffer = await blob.arrayBuffer();

            // 使用Uint8Array来访问ArrayBuffer中的每个字节  
            const uint8Array = new Uint8Array(arrayBuffer);

            // 初始化一个字符串用于存放最终的十六进制表示  
            let hexString = '';

            // 遍历Uint8Array  
            for (let i = 0; i < uint8Array.length; i++) {
                // 将每个字节转换为两位的十六进制字符串，并添加到hexString中  
                hexString += uint8Array[i].toString(16).padStart(2, '0');

                // 每16个字节后添加换行符  
                if ((i + 1) % 16 === 0) {
                    hexString += '\n';
                }
            }

            // 如果最后一组不足16个字节，则可能不需要添加换行符，但上面的逻辑已经正确处理了这一点  

            return hexString.trim();
        }

        require(['vs/editor/editor.main'], function () {
            const diffEditor = monaco.editor.createDiffEditor(document.getElementById('container'), {});
            const url = new URL(location.href);
            const myurl = '/api/v4.8/api/dumpfile' + ((url.searchParams.get('autodump')) ? '?autodump=true' : '');

            const a = new URL(myurl, location.href);
            a.searchParams.append('filename', url.searchParams.get('a'));
            const b = new URL(myurl, location.href);
            b.searchParams.append('filename', url.searchParams.get('b'));
            Promise.all([fetch(a),fetch(b)]).then(async function (r) {
                const originalTxt = '文件 ' + url.searchParams.get('a') + '\n' + groupHex(await formatHex(await r[0].blob()));
                const modifiedTxt = '文件 ' + url.searchParams.get('b') + '\n' + groupHex(await formatHex(await r[1].blob()));

                diffEditor.setModel({
                    original: monaco.editor.createModel(originalTxt, 'markdown'),
                    modified: monaco.editor.createModel(modifiedTxt, 'markdown')
                });

                window.addEventListener('resize', () => {
                    diffEditor.layout({
                        width: window.innerWidth,
                        height: window.innerHeight,
                    });
                });
            });
        });
    </script>
</body>
</html>